package com.tian.config;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2025-02-20 11:04
 * {@code @version:} 1.0
 */
@Slf4j
@Component
public class DelayDeleteCacheTask {
    public static final int DEFAULT_DELAY_MILLIS_SECONDS =1000;
    @Resource
    private ThreadPoolTaskScheduler taskScheduler;
    @Resource
    private RedissonClient redissonClient;

    /**
     * 延迟删除redis缓存
     *
     * @param key                redis缓存key
     * @param delayMillisSeconds 延迟时间,单位毫秒 ,默认1000毫秒
     */
    public void delayDelete(String key, int delayMillisSeconds) {
        Date delayDate = add(new Date(), delayMillisSeconds);
        taskScheduler.schedule(() -> {
            log.info("删除缓存：{}", key);
            redissonClient.getBucket(key).delete();
        }, delayDate);
    }

    private static Date add(Date date, int delayMillisSeconds) {
        if (delayMillisSeconds <= 0) {
            //默认1000毫秒
            delayMillisSeconds = DEFAULT_DELAY_MILLIS_SECONDS;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MILLISECOND, delayMillisSeconds);
        return calendar.getTime();
    }
}
